package com.cq.ssm.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;


//自定义全局异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver{

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		//handler就是处理器适配器要执行的Handler对象（只有method）
		//解析出异常类型
		//如果该异常类型是系统自定义异常，直接取出异常信息，在错误页面展示
		CustomException customException = null;
		System.out.println(ex);
		if(ex instanceof CustomException){
			customException = (CustomException)ex;
		}else{
			//如果该异常类型不是系统自定义的异常，构造一个自定义的异常类型
			customException = new CustomException("未知错误");
		}
		//错误信息
		String message = customException.getMessage();
		
		ModelAndView modelAndView = new ModelAndView();
		//将错误信息传到页面
		modelAndView.addObject("message", message);
		//指向错误页面
		modelAndView.setViewName("error");
		return modelAndView;
	}
}
